//
//  GoldPriceViewController.m
//  AppFrameWork
//
//  Created by Le Anh Tai on 7/21/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "GoldPriceViewController.h"
#import "GoldPriceCell.h"
#import "UIConstants.h"
#import "SyncHttpRequest.h"
#import "DOMParser.h"
#import "Utility.h"
#import "Reachability.h"
#import "UIImage+Color.h"
#import "RootViewControler.h"
#import "Database.h"

@interface GoldPriceViewController ()

@end

@implementation GoldPriceViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // Custom initialization
        self.title = TEXT_TITLE_GOLD_PRICE;
        self.iconImage = @"iconGoldPrice.png";        
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];    
    
    //
    _titleLabel.textColor = COLOR_WHITE_NORMAL;
    _titleLabel.backgroundColor = COLOR_BLACK_NORMAL;//COLOR(216, 208, 187, 1);
    
    //refresh button
    UIImage *img = [[UIImage imageNamed:@"btnRefesh.png"] imageWithTint:COLOR_BLUE_IOS7];
    [_refreshButton setImage:img forState:UIControlStateNormal];
    
    //
    [self.worldGoldPriceLabel setText:@"Mua: 1320, Bán: 1342"];
    
    //
    _fetchingSJCGoldPrice = NO;
    
    _preGoldPricesDic = [[Database sharedInstance] objectForKey:PREV_GOLD_PRICE_KEY];
    _goldPricesDic = [[Database sharedInstance] objectForKey:CURR_GOLD_PRICE_KEY];
    
    //
    if (!IS_IPHONE)
    {
        [self fetchSJCGoldPrice];
    }
    
//    _refreshGoldPriceThreadStatus = ThreadRun;
//    [self refreshGoldPriceThreadProc];
    
    _pullToRefreshView = [[PullToRefreshView alloc] initWithScrollView:(UIScrollView *) self.tableView];
    [_pullToRefreshView setDelegate:self];
    [self.tableView addSubview:_pullToRefreshView];
    
    _detailCallOut = [[DetailUpDownPriceCallOutView alloc]init];
    _detailCallOut.mainDelegate = self;
    
    [self loadLastIndexPath];
    
    _tableView.backgroundColor = COLOR(40, 40, 40, 1);    
}

- (void)reloadLanguage
{
    self.title = TEXT_TITLE_GOLD_PRICE;
    
    _typeLabel.text = NSLocalizedString(@"Loại vàng", nil);
    _sellLabel.text = NSLocalizedString(@"Bán", nil);
    _buyLabel.text = NSLocalizedString(@"Mua", nil);
    _unitLabel.text = NSLocalizedString(@"(Đơn vị: Ngàn đồng/Lượng)", nil);;
    
    _titleLabel.text = [NSString stringWithFormat:NSLocalizedString(_curUpdateString, nil), [_lastUpdate stringWithFormat:DISPLAY_DATE_FORMAT] ];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (_lastContentOffsetY)
    {
        [UIView animateWithDuration:0.4 animations:^{
           _tableView.contentOffset = CGPointMake(0, _lastContentOffsetY);
        }];
        
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _lastContentOffsetY = _tableView.contentOffset.y;
}

- (void)loadTheme:(BOOL)isDarkTheme
{
    if (isDarkTheme)
    {
        _titleLabel.textColor = COLOR_WHITE_NORMAL;
        _titleLabel.backgroundColor = COLOR_LIGHT_BLACK;//COLOR(216, 208, 187, 1);
        _headerView.backgroundColor = COLOR_BACKGROUND_HEADER_DARK;//COLOR(77, 77, 77, 1);
        
        NSArray *subviews = _headerView.subviews;
        for (UILabel *label in subviews) {
            if ([label isKindOfClass:[UILabel class]] == NO)
            {
                continue;
            }
            
            label.textColor = COLOR_TEXT_ORANGE_DARK;
        }
        
        _pullToRefreshView.backgroundColor = COLOR_BACKGROUND_PULL_TO_REFRESH_DARK;
    }
    else
    {
        _titleLabel.textColor = COLOR_TEXT_HEADER_LIGHT;
        _titleLabel.backgroundColor = COLOR_WHITE_NORMAL;//COLOR(216, 208, 187, 1);
        _headerView.backgroundColor = COLOR_BACKGROUND_LIGHT;
        
        NSArray *subviews = _headerView.subviews;
        for (UILabel *label in subviews) {
            if ([label isKindOfClass:[UILabel class]] == NO)
            {
                continue;
            }
            
            label.textColor = COLOR_TEXT_ORANGE_LIGHT;
        }
        
        _pullToRefreshView.backgroundColor = COLOR_BACKGROUND_PULL_TO_REFRESH_LIGHT;
    }
}


- (void)pullToRefreshViewShouldRefresh:(PullToRefreshView *)view;
{
    [self refreshButtonPressed:nil];
    [_pullToRefreshView finishedLoading];
}

- (NSDate*)getCurrentUpdateDate
{
    NSDate *updatedDate = [_goldPricesDic objectForKey:KEY_UPDATED_DATE];
    return updatedDate;
}

- (NSDate*)getPreviousUpdateDate
{
    NSDate *preUpdatedDate = [_preGoldPricesDic objectForKey:KEY_UPDATED_DATE];
    return preUpdatedDate;
}

#pragma mark - Fetch gold price
- (void)fetchSJCGoldPrice
{
    _curUpdateString = @"Đang cập nhật...";
    _titleLabel.text = NSLocalizedString(_curUpdateString, nil);
    [self performSelectorInBackground:@selector(performFetchingSJCGoldPrice) withObject:nil];
}

- (void)performFetchingSJCGoldPrice
{
    if (_fetchingSJCGoldPrice == YES)
    {
        return;
    }

    _fetchingSJCGoldPrice = YES;
    
    NSDate *updatedDate_old = nil;
    
    if (_goldPricesDic)
    {
        updatedDate_old = [_goldPricesDic objectForKey:KEY_UPDATED_DATE];
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:SJC_GOLD_PRICE_URL]];
    __block NSData *_data = nil;
    
    [SyncHttpRequest connectionWithRequest:request callback:^(NSData *data)
     {
         _data = data;
     }];
    
    if (_data == nil)
    {
        _fetchingSJCGoldPrice = NO;

        [self loadGoldPriceOffline];

        return;
    }
    
    //
    NSString *xml = [[NSString alloc] initWithBytes:[_data bytes] length:[_data length] encoding:NSUTF8StringEncoding];
    if (xml == nil)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    if ([xml hasPrefix:@"<?xml"] == NO)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    NSArray *nodes = [DOMParser queryXMLNodesByXPath:xml xpath:XPATH_SJC_GOLD_PRICE namespaceS:nil namespaceNS2:nil];
    if (nodes == nil || [nodes count] == 0)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    //
    NSDictionary *nodeRateList = [Utility getObject:nodes atIndex:0];
    if (nodeRateList == nil)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    //
    NSDictionary *rateListAttribute = [nodeRateList objectForKey:KEY_NODE_ATTRIBUTE];
    if (rateListAttribute == nil)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    NSString *date = [rateListAttribute objectForKey:@"updated"];
    if (date == nil)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    NSDate *updateDate = [NSDate dateWithFormat:GOLD_PRICES_UPDATED_DATE_FORMAT AndValue:date];
    if (updateDate == nil)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    //
    if (_goldPricesDic)
    {
        if ([Utility isDate:updatedDate_old ssGreaterOrEqualDate:updateDate])
        {
            NSLog(@"Do not need to update gold price");
            
            _fetchingSJCGoldPrice = NO;
            
            [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
            
            [self performSelectorOnMainThread:@selector(showMessageUpdated:) withObject:NSLocalizedString(@"Giá vàng đã mới nhất", nil) waitUntilDone:NO];
            
            return;
        }
    }
    
    //
    NSArray *citys = [nodeRateList objectForKey:KEY_NODE_CHILD];
    if (citys == nil)
    {
        _fetchingSJCGoldPrice = NO;
        
        [self performSelectorOnMainThread:@selector(showUpdatedDate:) withObject:updatedDate_old waitUntilDone:NO];
        
        return;
    }
    
    NSMutableArray *goldPrices = [[NSMutableArray alloc] init];
    
    for (NSDictionary *city in citys)
    {
        NSDictionary *attributes = [city objectForKey:KEY_NODE_ATTRIBUTE];
        if (attributes == nil)
        {
            continue;
        }
        
        NSString *key = [attributes objectForKey:@"name"];
        if (key == nil)
        {
            continue;
        }
        
        NSMutableArray *cityItems = nil;
        NSArray *items = [city objectForKey:KEY_NODE_CHILD];
        
        for (NSDictionary *item in items)
        {
            if (item == nil)
            {
                continue;
            }
            
            NSDictionary* itemAttributes = [item objectForKey:KEY_NODE_ATTRIBUTE];
            if (itemAttributes == nil)
            {
                continue;
            }
            
            if (cityItems == nil)
            {
                cityItems = [[NSMutableArray alloc] init];
            }
            
            NSString *typeValue = [itemAttributes objectForKey:@"type"];
            NSString *buyValue = [itemAttributes objectForKey:@"buy"];
            NSString *sellValue = [itemAttributes objectForKey:@"sell"];
            
            if (typeValue == nil || buyValue == nil || sellValue == nil)
            {
                continue;
            }
            
            [cityItems addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                  typeValue, GOLD_CODE_KEY,
                                  buyValue, GOLD_BUY_KEY,
                                  sellValue, GOLD_SELL_KEY, nil]];
        }
        
        if (cityItems)
        {
            NSMutableDictionary *goldPriceDictionary = [[NSMutableDictionary alloc] init];
            [goldPriceDictionary setObject:key forKey:PRICE_CITY_KEY];
            [goldPriceDictionary setObject:cityItems forKey:PRICE_CITY_ITEMS_KEY];
            
            [goldPrices addObject:goldPriceDictionary];
        }
    }
    
    NSMutableDictionary *goldPricesDic = nil;
    
    if (goldPrices.count == 0 || updateDate == nil)
    {
        _fetchingSJCGoldPrice = NO;
        return;
    }
    
    if ([goldPrices count] > 0)
    {
        goldPricesDic = [[NSMutableDictionary alloc] init];
        [goldPricesDic setObject:updateDate forKey:KEY_UPDATED_DATE];
        [goldPricesDic setObject:goldPrices forKey:KEY_GOLD_PRICES];
    }

    //
    [self performSelectorOnMainThread:@selector(updateSJCGoldPrice:) withObject:goldPricesDic waitUntilDone:NO];
}

- (void)showUpdatedDate:(NSDate *)updatedDate
{
    NSString *text;
    
    if (updatedDate)
    {
        _lastUpdate = updatedDate;
        _curUpdateString = @"Cập nhật lúc: %@";
        text = [NSString stringWithFormat:NSLocalizedString(_curUpdateString, nil), [updatedDate stringWithFormat:DISPLAY_DATE_FORMAT]];
    }
    else
    {
        _lastUpdate = nil;
        _curUpdateString = @"Bị lỗi trong quá trình cập nhật";
        text = NSLocalizedString(_curUpdateString, nil);
    }
    
    _titleLabel.text = text;
}

- (void)loadGoldPriceOffline
{
    NSLog(@"Load gold prices offline");

    if (_goldPricesDic)
    {
        [self performSelectorOnMainThread:@selector(updateSJCGoldPrice:) withObject:_goldPricesDic waitUntilDone:NO];
    }
    else
    {
        _curUpdateString = @"Chưa có dữ liệu offline";
        _titleLabel.text = NSLocalizedString(_curUpdateString, nil);
    }
}

- (void)showMessageUpdated:(NSString*)string
{
    if (_isPressedRefresh)
    {
        _isPressedRefresh = NO;

        [Utility showInfoMsg:string inView:self.view];
    }
}

- (void)updateSJCGoldPrice:(NSMutableDictionary *)goldPricesDic
{
    BOOL reloadTable = NO;
    
    if ([_goldPricesDic isEqual:goldPricesDic])
    {
        reloadTable = YES;
    }
    else
    {
        if (goldPricesDic)
        {
            reloadTable = YES;
            
            //
            if (_goldPricesDic)
            {
                _preGoldPricesDic = _goldPricesDic;
                [[Database sharedInstance] setObject:_preGoldPricesDic forKey:PREV_GOLD_PRICE_KEY];
            }
            
            //
            _goldPricesDic = goldPricesDic;
            [[Database sharedInstance] setObject:_goldPricesDic forKey:CURR_GOLD_PRICE_KEY];
            
            [[Database sharedInstance] save];
        }
        else
        {
            assert(0);
        }
    }
    
    [self updateSJCGoldPriceUI:[_goldPricesDic objectForKey:KEY_UPDATED_DATE] reloadTable:reloadTable];
}

- (void)updateSJCGoldPriceUI:(NSDate *)updatedDate reloadTable:(BOOL)reloadTable
{
    NSLog(@"Update gold price");
    
    _fetchingSJCGoldPrice = NO;
    
    if (reloadTable)
    {
        [_tableView reloadData];
    }

    [self showUpdatedDate:updatedDate];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    NSInteger paddingRight = 20;
    NSInteger typeWid = 3*(self.view.width - paddingRight)/5;
    NSInteger priceWid = (self.view.width - paddingRight)/5;
    
    _typeLabel.frame = RECT(0, _typeLabel.top, typeWid, _typeLabel.height);
    _unitLabel.frame = RECT(0, _unitLabel.top, typeWid, _unitLabel.height);
    _buyLabel.frame = RECT(_typeLabel.right, _typeLabel.top, priceWid, _buyLabel.height);
    _sellLabel.frame = RECT(_buyLabel.right, _typeLabel.top, self.view.width - _buyLabel.right - paddingRight, _sellLabel.height);
    
    if (_detailCallOut.superview && _selectedIndexPath)
    {
        [self positioningCalloutAtIndexPath:_selectedIndexPath];
    }
}

- (void)saveLastIndexPath
{
    _lastContentOffsetY = _tableView.contentOffset.y;
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:_lastContentOffsetY] forKey:@"LastIndexPathGoldPrice"];
}

- (void)loadLastIndexPath
{
    _lastContentOffsetY = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LastIndexPathGoldPrice"] integerValue];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_goldPricesDic == nil)
    {
        return 0;
    }
    
    NSArray *goldPrices = [_goldPricesDic objectForKey:KEY_GOLD_PRICES];
    if (goldPrices == nil)
    {
        return 0;
    }
    

    return [goldPrices count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 24;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray *goldPrices = [_goldPricesDic objectForKey:KEY_GOLD_PRICES];
    NSDictionary *city = [Utility getObject:goldPrices atIndex:section];
    NSString *title = [city objectForKey:PRICE_CITY_KEY];

    HeaderGoldPriceView *headerView = [[HeaderGoldPriceView alloc] init];
    headerView.titleLabel.text = title;
    headerView.mainDelegate = self;

    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *goldPrices = [_goldPricesDic objectForKey:KEY_GOLD_PRICES];
    NSDictionary *city = [Utility getObject:goldPrices atIndex:section];
    NSMutableArray *items = [city objectForKey:PRICE_CITY_ITEMS_KEY];
    
    if (items == nil)
    {
        return 0;
    }
    
    return [items count];
}

- (NSDictionary*)getGoldPriceDataAtSection:(NSInteger)section row:(NSInteger)row
{
    //
    NSDictionary *preData = nil;
    NSString *preGoldType = nil;
    
    if (_preGoldPricesDic)
    {
        NSArray *preGoldPrices = [_preGoldPricesDic objectForKey:KEY_GOLD_PRICES];
        NSDictionary *preCity = [Utility getObject:preGoldPrices atIndex:section];
        NSMutableArray *preGoldPrice = [preCity objectForKey:PRICE_CITY_ITEMS_KEY];
        
        preData = [Utility getObject:preGoldPrice atIndex:row];
        preGoldType = [preData objectForKey:GOLD_CODE_KEY];
    }
    
    //
    NSArray *goldPrices = [_goldPricesDic objectForKey:KEY_GOLD_PRICES];
    NSDictionary *city = [Utility getObject:goldPrices atIndex:section];
    NSMutableArray *goldPrice = [city objectForKey:PRICE_CITY_ITEMS_KEY];
    NSDictionary *data = [Utility getObject:goldPrice atIndex:row];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:data];
    
    if (preData && [preGoldType isEqualToString:[data objectForKey:GOLD_CODE_KEY]])
    {
        [dict setObject:[preData objectForKey:GOLD_BUY_KEY] forKey:PRE_GOLD_BUY_KEY];
        [dict setObject:[preData objectForKey:GOLD_SELL_KEY] forKey:PRE_GOLD_SELL_KEY];
    }
    
    return dict;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    
    static NSString *identifier = @"GoldPriceCell";
    GoldPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil)
    {
        cell = [[GoldPriceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }

    NSDictionary *dict = [self getGoldPriceDataAtSection:indexPath.section row:row];

    [cell loadDataWithDictionary:dict];
    
    if (_selectedIndexPath && _selectedIndexPath.row == indexPath.row && _selectedIndexPath.section == indexPath.section)
    {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self showDataCalloutView];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if (_selectedIndexPath && _selectedIndexPath.row == indexPath.row && _selectedIndexPath.section == indexPath.section)
    {
        _selectedIndexPath = nil;
        [self removeCalloutView];
        
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        
        return;
    }
    
    [self addCalloutView];
    [self positioningCalloutAtIndexPath:indexPath];
    _selectedIndexPath = indexPath;
    
    [self showDataCalloutView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self removeCalloutView];
}

#pragma mark - CALL OUT
- (void)showDataCalloutView
{
    if (_selectedIndexPath == nil)
    {
        return;
    }
    
    NSInteger row = _selectedIndexPath.row;    
    NSDictionary *dict = [self getGoldPriceDataAtSection:_selectedIndexPath.section row:row];
    NSString *lastDate = [[self getPreviousUpdateDate] stringWithFormat:DISPLAY_DATE_FORMAT_SHORT];
    NSString *curDate = [[self getCurrentUpdateDate] stringWithFormat:DISPLAY_DATE_FORMAT_SHORT];
    [_detailCallOut loadDataWithGoldPriceDictionary:dict lastDate:lastDate currentDate:curDate];
}

- (void)detailUpDownPriceCalloutViewouchOutSide:(CalloutView *)view atPoint:(CGPoint)point
{
    CGPoint convertPoint = [self.view convertPoint:point fromView:view];
    if ( CGRectContainsPoint(self.tableView.frame, convertPoint) )
    {
        return;
    }
    
    if (_selectedIndexPath)
    {
        _selectedIndexPath = nil;
        [_tableView selectRowAtIndexPath:nil animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self removeCalloutView];
    }
}

- (void)headerGoldPriceViewDidTap:(UIView *)view atPoint:(CGPoint)point
{
    if (_selectedIndexPath == nil)
    {
        return;
    }
    
    _selectedIndexPath = nil;
    [_tableView selectRowAtIndexPath:nil animated:NO scrollPosition:UITableViewScrollPositionNone];
    [self removeCalloutView];
}

- (CGRect)detailUpDownPriceCalloutViewRectForSelectedIndex:(CalloutView *)view
{
    if (_selectedIndexPath == nil || [_tableView cellForRowAtIndexPath:_selectedIndexPath] == nil)
    {
        return CGRectZero;
    }
    
    return [[DataSingleton shared].rootViewController.view convertRect:[_tableView rectForRowAtIndexPath:_selectedIndexPath] fromView:_tableView];
}

- (void)removeCalloutView
{
    if (_detailCallOut && _detailCallOut.superview)
    {
        [_detailCallOut removeFromSuperview];
    }
}

- (void)addCalloutView
{
    if (!_detailCallOut.superview)
    {        
        [[DataSingleton shared].rootViewController.view addSubview:_detailCallOut];
        
        _detailCallOut.alpha = 0;
        
        [UIView animateWithDuration:0.4 animations:^{
            _detailCallOut.alpha = 1;
        }];
    }
}

- (void)positioningCalloutAtIndexPath:(NSIndexPath*)indexPath
{
    CGRect rect = [_tableView rectForRowAtIndexPath:indexPath];
    rect.origin = [[DataSingleton shared].rootViewController.view convertPoint:rect.origin fromView:_tableView];
    CGRect calloutRect;
    
    calloutRect.size.width = self.view.width;
    calloutRect.size.height = 115;
    calloutRect.origin.x = rect.origin.x;
    calloutRect.origin.y = rect.origin.y - calloutRect.size.height;
            
    [_detailCallOut setFrame:RECT(calloutRect.origin.x, calloutRect.origin.y, calloutRect.size.width, calloutRect.size.height)];
}

- (void)viewDidUnload
{
    [self setTypeLabel:nil];
    [self setSellLabel:nil];
    [self setBuyLabel:nil];
    [self setWorldGoldPriceLabel:nil];
    [self setUnitLabel:nil];
    [self setRefreshButton:nil];
    [super viewDidUnload];
}

- (void)deactive
{
    _refreshGoldPriceThreadStatus = ThreadPause;
}

- (void)active
{
    _refreshGoldPriceThreadStatus = ThreadRun;
    [self fetchSJCGoldPrice];
}

//#pragma mark - Refresh Gold Price Thread
//- (void)refreshGoldPriceThreadProc
//{
//    dispatch_queue_t _refreshGoldPriceThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    
//    dispatch_async(_refreshGoldPriceThread, ^{
//        while (_refreshGoldPriceThreadStatus != ThreadStop)
//        {
//            if (_refreshGoldPriceThreadStatus == ThreadPause)
//            {
//                [NSThread sleepForTimeInterval:5.0f];
//                NSLog(@"Pause update gold prices");
//                continue;
//            }
//            
//            [NSThread sleepForTimeInterval:UPDATE_GOLD_PRICE_INTERVAL];
//            
//            [self performFetchingSJCGoldPrice];
//        }
//    });
//}

- (void)hideLoading
{
    [Utility hideLoading:self.view];
}

- (IBAction)refreshButtonPressed:(id)sender
{
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable)
    {
        [Utility showLoading:self.view withMsg:NSLocalizedString(@"Chưa kết nối mạng", nil)];
        [self performSelector:@selector(hideLoading) withObject:nil afterDelay:1.5];
    }
    else
    {
        _isPressedRefresh = YES;
        [self fetchSJCGoldPrice];
    }
}

- (void)dealloc
{
    _refreshGoldPriceThreadStatus = ThreadStop;
    
    [_goldPricesDic removeAllObjects];
    _goldPricesDic = nil;
}
@end
